package org.soc.timesheet.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.RandomStringUtils;
import org.soc.timesheet.custom.domain.filters.UserFilter;
import org.soc.timesheet.domain.Roles;
import org.soc.timesheet.domain.Users;
import org.soc.timesheet.domain.UsersLogged;
import org.soc.timesheet.server.domain.service.CommonService;
import org.soc.timesheet.server.domain.service.CustomersEnabledService;
import org.soc.timesheet.server.domain.service.EmailsService;
import org.soc.timesheet.server.domain.service.RolesService;
import org.soc.timesheet.server.domain.service.TimesheetService;
import org.soc.timesheet.server.domain.service.TokenTypeService;
import org.soc.timesheet.server.domain.service.UsersLoggedService;
import org.soc.timesheet.server.domain.service.UsersProjectService;
import org.soc.timesheet.server.domain.service.UsersService;
import org.soc.timesheet.util.ControllerAttributesContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RequestMapping("/userses")
@Controller
@RooWebScaffold(path = "userses", formBackingObject = Users.class)
@RooWebJson(jsonObject = Users.class)
public class UsersController {

	@Autowired
	HttpServletRequest request;
	
	@Autowired
	HttpServletResponse response;

	@Autowired
	EmailsService emailsService;

	@Autowired
	UsersLoggedService usersLoggedService;

	@Autowired
	TokenTypeService tokenTyeService;
	
	
	@Autowired
	CommonService commonService;
	
	@Autowired
	@Qualifier(value = "mailSender")
	JavaMailSender mailSender;

	@RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
	@ResponseBody
	public ResponseEntity<String> showJson(@PathVariable("id") Integer id) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json; charset=utf-8");
		try {
			Users users = usersService.findUsers(id);
			if (users == null) {
				return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
			}
			return new ResponseEntity<String>(users.toJson(), headers,
					HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(value = "/{page}/{limit}", headers = "Accept=application/json", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Page<Users>> findAll(@PathVariable("page") int page,
			@PathVariable("limit") int size,
			@RequestHeader(value = "filters", required = false) String filters)
			throws Exception {
		PageRequest pageRequest = new PageRequest(page, size);
		if (filters != null && !filters.equals("")) {
			return findByFilters(filters, pageRequest);
		}
		return find(pageRequest);
	}

	private ResponseEntity<Page<Users>> find(PageRequest pageRequest) {
		HttpHeaders headers = getHeaders();
		Page<Users> result = usersService.findAll(pageRequest);
		return new ResponseEntity<Page<Users>>(result, headers, HttpStatus.OK);
	}

	private ResponseEntity<Page<Users>> findByFilters(String filters,
			PageRequest pageRequest) throws IOException, JsonParseException,
			JsonMappingException {
		ObjectMapper mapper = new ObjectMapper();
		UserFilter filter = mapper.readValue(filters,
				new TypeReference<UserFilter>() {
				});
		Page<Users> page = usersService.findByFilters(filter, pageRequest);
		return new ResponseEntity<Page<Users>>(page, getHeaders(),
				HttpStatus.OK);
	}

	private HttpHeaders getHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		return headers;
	}

	@RequestMapping(headers = "Accept=application/json")
	@ResponseBody
	public ResponseEntity<String> listJson() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json; charset=utf-8");
		try {
			List<Users> result = usersService.findAllUserses();
			return new ResponseEntity<String>(Users.toJsonArray(result),
					headers, HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
	public ResponseEntity<String> createFromJson(@RequestBody String json,
			UriComponentsBuilder uriBuilder) {
		HttpHeaders headers = new HttpHeaders();
//		if(referer==null || referer.trim().equals("")){
//			referer="http://"+request.getLocalAddr()+":"+request.getLocalPort()+"/"+request.getServletContext().getContextPath();
//		}
		String referer = ControllerAttributesContainer.getReferer();
		headers.add("Content-Type", "application/json");
		try {
			final Users users = Users.fromJsonToUsers(json);

			// genero un token di RECOVERY! La procedura di LOGIN è la medesima
			// di un recupero password.
			UsersLogged logged = commonService.createUser(users);
			
			final String token = RandomStringUtils.randomAlphanumeric(200);
			logged.setToken(token);

			RequestMapping a = (RequestMapping) getClass().getAnnotation(
					RequestMapping.class);
			headers.add(
					"Location",
					uriBuilder
							.path(a.value()[0] + "/" + users.getId().toString())
							.build().toUriString());
			return new ResponseEntity<String>(headers, HttpStatus.CREATED);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
	public ResponseEntity<String> createFromJsonArray(@RequestBody String json) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		try {
			for (Users users : Users.fromJsonArrayToUserses(json)) {
				usersService.saveUsers(users);
			}
			return new ResponseEntity<String>(headers, HttpStatus.CREATED);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, headers = "Accept=application/json")
	public ResponseEntity<String> updateFromJson(@RequestBody String json,
			@PathVariable("id") Integer id) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		try {
			Users users = Users.fromJsonToUsers(json);
			users.setId(id);
			if (usersService.updateUsers(users) == null) {
				return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
			}
			return new ResponseEntity<String>(headers, HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
	public ResponseEntity<String> deleteFromJson(@PathVariable("id") Integer id) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		try {
			Users users = usersService.findUsers(id);
			if (users == null) {
				return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
			}
			usersService.deleteUsers(users);
			return new ResponseEntity<String>(headers, HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(params = "find=ByIdRole", headers = "Accept=application/json")
	@ResponseBody
	public ResponseEntity<String> jsonFindUsersesByIdRole(
			@RequestParam("idRole") Roles idRole) {
		HttpHeaders headers = new HttpHeaders();
		try {
			headers.add("Content-Type", "application/json; charset=utf-8");
			return new ResponseEntity<String>(Users.toJsonArray(Users
					.findUsersesByIdRole(idRole).getResultList()), headers,
					HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(params = "find=ByLogin", headers = "Accept=application/json")
	@ResponseBody
	public ResponseEntity<String> jsonFindUsersesByLogin(
			@RequestParam("login") String login) {
		HttpHeaders headers = new HttpHeaders();
		try {
			headers.add("Content-Type", "application/json; charset=utf-8");
			return new ResponseEntity<String>(Users.toJsonArray(Users
					.findUsersesByLogin(login).getResultList()), headers,
					HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping(params = "find=ByLoginEquals", headers = "Accept=application/json")
	@ResponseBody
	public ResponseEntity<String> jsonFindUsersesByLoginEquals(
			@RequestParam("login") String login) {
		HttpHeaders headers = new HttpHeaders();
		try {
			headers.add("Content-Type", "application/json; charset=utf-8");
			return new ResponseEntity<String>(Users.toJsonArray(Users
					.findUsersesByLoginEquals(login).getResultList()), headers,
					HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<String>("{\"ERROR\":" + e.getMessage()
					+ "\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@Autowired
	UsersService usersService;

	@Autowired
	CustomersEnabledService customersEnabledService;

	@Autowired
	RolesService rolesService;

	@Autowired
	TimesheetService timesheetService;

	@Autowired
	UsersProjectService usersProjectService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
	public String create(@Valid Users users, BindingResult bindingResult,
			Model uiModel, HttpServletRequest httpServletRequest) {
		if (bindingResult.hasErrors()) {
			populateEditForm(uiModel, users);
			return "userses/create";
		}
		uiModel.asMap().clear();
		usersService.saveUsers(users);
		return "redirect:/userses/"
				+ encodeUrlPathSegment(users.getId().toString(),
						httpServletRequest);
	}

	@RequestMapping(params = "form", produces = "text/html")
	public String createForm(Model uiModel) {
		populateEditForm(uiModel, new Users());
		return "userses/create";
	}

	@RequestMapping(value = "/{id}", produces = "text/html")
	public String show(@PathVariable("id") Integer id, Model uiModel) {
		uiModel.addAttribute("users", usersService.findUsers(id));
		uiModel.addAttribute("itemId", id);
		return "userses/show";
	}

	@RequestMapping(produces = "text/html")
	public String list(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			@RequestParam(value = "sortFieldName", required = false) String sortFieldName,
			@RequestParam(value = "sortOrder", required = false) String sortOrder,
			Model uiModel) {
		if (page != null || size != null) {
			int sizeNo = size == null ? 10 : size.intValue();
			final int firstResult = page == null ? 0 : (page.intValue() - 1)
					* sizeNo;
			uiModel.addAttribute("userses", Users.findUsersEntries(firstResult,
					sizeNo, sortFieldName, sortOrder));
			float nrOfPages = (float) usersService.countAllUserses() / sizeNo;
			uiModel.addAttribute(
					"maxPages",
					(int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
							: nrOfPages));
		} else {
			uiModel.addAttribute("userses",
					Users.findAllUserses(sortFieldName, sortOrder));
		}
		return "userses/list";
	}

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
	public String update(@Valid Users users, BindingResult bindingResult,
			Model uiModel, HttpServletRequest httpServletRequest) {
		if (bindingResult.hasErrors()) {
			populateEditForm(uiModel, users);
			return "userses/update";
		}
		uiModel.asMap().clear();
		usersService.updateUsers(users);
		return "redirect:/userses/"
				+ encodeUrlPathSegment(users.getId().toString(),
						httpServletRequest);
	}

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
	public String updateForm(@PathVariable("id") Integer id, Model uiModel) {
		populateEditForm(uiModel, usersService.findUsers(id));
		return "userses/update";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
	public String delete(@PathVariable("id") Integer id,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			Model uiModel) {
		Users users = usersService.findUsers(id);
		usersService.deleteUsers(users);
		uiModel.asMap().clear();
		uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
		uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
		return "redirect:/userses";
	}

	void populateEditForm(Model uiModel, Users users) {
		uiModel.addAttribute("users", users);
		uiModel.addAttribute("customersenableds",
				customersEnabledService.findAllCustomersEnableds());
		uiModel.addAttribute("roleses", rolesService.findAllRoleses());
		uiModel.addAttribute("timesheets", timesheetService.findAllTimesheets());
		uiModel.addAttribute("usersloggeds",
				usersLoggedService.findAllUsersLoggeds());
		uiModel.addAttribute("usersprojects",
				usersProjectService.findAllUsersProjects());
	}

	String encodeUrlPathSegment(String pathSegment,
			HttpServletRequest httpServletRequest) {
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {
		}
		return pathSegment;
	}
}
